<template>
	<view>
		<view class="background">
			<view class="title">
				<text>上传任务完成图片</text>
				<text style="font-size: 25rpx;color: red;">
					（文件大小3MB以内）
				</text>
			</view>
			<view style="width: 235rpx;height: 350rpx;margin: 30rpx auto;">
				<uni-file-picker ref="file" v-model="imageValue" fileMediatype="image" mode="grid" limit="1"
					:image-styles="imageStyles" :auto-upload="false" @select="uploadSelect" @success="uploadSuccess"
					@fail="uploadFail">
					<view class="file-add-background">
						<view class="file-add-icon-background">
							<u--image src="/static/upload-image.png" width="60px" height="60px" />
						</view>
						<text>选择图片</text>
					</view>
				</uni-file-picker>
			</view>
			<u-button type="success" @click="upload">确认上传</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imageValue: [],
				imageStyles: {
					"height": "500rpx",
					"width": "100%",
					"border": {
						"color": "#eee",
						"width": "2px",
						"style": "solid",
					}
				},
				taskForm: null
			}
		},
		onLoad(option) {
			if (option.id) {
				this.$http.get(`/taskList/get/${option.id}`)
					.then((res) => {
						this.taskForm = res.data
						if (this.taskForm.images) {
							this.imageValue = [{
								url: this.taskForm.images
							}]
						}
					}).catch((err) => {
						console.log(err);
					})
			}
		},
		methods: {
			uploadSelect(e) {
				if (e.tempFiles[0].size > 1 * 1024 * 1024) {
					this.$refs.avatarFile.clearFiles();
					uni.$u.toast('文件过大，请压缩后上传');
					return;
				}
			},
			upload() {
				if (this.vuex_user.status === 0) {
					uni.$u.toast('请先绑定伴侣');
					return;
				}

				uni.showLoading({
					title: '操作中',
					mask: true
				});

				this.$refs.file.upload();

			},
			uploadSuccess(e) {
				this.$http.post("/taskList/update", {
					id: this.taskForm.id,
					images: this.imageValue[0].url
				}).then((res) => {
						this.taskForm.images = this.imageValue[0].url

						let pages = getCurrentPages(),
							prevPage = pages[pages.length - 2],
							list = prevPage.$vm.list,
							index = list.findIndex(item => item.id === this.taskForm.id),
							taskItem = list[index].images = this.taskForm.images

						list.splice(index, 1, taskItem)
						uni.hideLoading();
						uni.$u.toast('上传成功');
					}).catch(err => {
						uni.hideLoading();
						uni.$u.toast(err.message)
					});
			},
			//上传失败
			uploadFail(e) {
				uni.hideLoading();
				uni.$u.toast('上传失败')
			},
		}
	}
</script>

<style>
	.background {
		margin: 50rpx 30rpx;
	}

	.file-add-background {
		width: 100%;
		height: 100%;
		background-color: rgb(250, 250, 250);
		text-align: center;
		color: #a5a5a5;
	}

	.file-add-icon-background {
		width: 60px;
		height: 60px;
		padding-top: 80rpx;
		margin: auto;
	}

	.title {
		font-size: 32rpx;
	}
</style>